//
//  ReleaseCircleVC.m
//  SelfDriving
//
//  Created by apple on 16/2/1.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "ReleaseCircleVC.h"
#import "ReleaseCell.h"
#import <AVFoundation/AVCaptureDevice.h>
#import <AVFoundation/AVMediaFormat.h>
#import "ReleaseCell.h"
#import "BusinessService+FJ.h"
@interface ReleaseCircleVC ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,MAMapViewDelegate,UITableViewDelegate,UITableViewDataSource,UITextViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *table;
@property (weak, nonatomic) IBOutlet UITextField *titlefield;

@end

@implementation ReleaseCircleVC
{
    NSMutableDictionary *locationdic;
    
    UIImage *imageData;
    NSURL *VideoPath;
    int filetype;
    MPMoviePlayerController *moviePlayer;
    UIView *shareView;
    NSData *videoData;
    NSMutableArray *data;
    NSMutableArray *sdata;
    MAMapView *_mapView;
    NSMutableArray *contentArr;
}
-(void)viewWillDisappear:(BOOL)animated
{
    [IQKeyboardManager sharedManager].enableAutoToolbar = YES;
    [IQKeyboardManager sharedManager].enable = YES;
}
-(void)viewWillAppear:(BOOL)animated{
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
    [IQKeyboardManager sharedManager].enable = NO;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter]
     addObserver:self
     selector:@selector(submitAction:)
     name:@"submitActions"
     object:nil];
    _mapView = [[MAMapView alloc]init];
    _mapView.showsUserLocation = YES;
    _mapView.delegate = self;
    _mapView.showsUserLocation = YES;
    
    data = [[NSMutableArray alloc]init];
    sdata = [[NSMutableArray alloc]init];
    contentArr = [[NSMutableArray alloc]init];
    NSMutableDictionary *d = [[NSMutableDictionary alloc]init];
    [d setObject:@"add" forKey:@"type"];
    [sdata addObject:d];
    
    if (_videoUrl) {
        filetype = 2;
        VideoPath = _videoUrl;
    }else{
        filetype = 1;
        imageData = _imgData;
    }
    contentArr = (NSMutableArray *)[TCSession getSessionListTimeLine];
    NSMutableArray *data1 = [[NSMutableArray alloc]init];
    for (int i = 0; i<contentArr.count ; i++) {
        TCSession *msg = [contentArr objectAtIndex:i];
        if (msg.typeChat == 100) {
            NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
            [dic setObject:msg.name forKey:@"nickname"];
            [dic setObject:msg.head forKey:@"headsmall"];
            [dic setObject:msg.ID forKey:@"uid"];
            [data1 addObject:dic];
        }
    }
    contentArr = data1;
    
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    [dic setObject:[NSNumber numberWithInt:1] forKey:@"page"];
    [SVProgressHUD showWithStatus:@"加载中..."];
    [dic setObject:@"2"   forKey:@"type"];

    [[BusinessService shareInstance]myfollow:dic success:^(id result) {
        [SVProgressHUD dismiss];
        data =  result;
        NSMutableArray *datas = [[NSMutableArray alloc]init];
        for (int i = 0 ; i<data.count; i++) {
            LoginResponseModel *user = [data objectAtIndex:i];
            NSMutableDictionary *dics = [[NSMutableDictionary alloc]init];
            [dics setObject:user.nickname==nil?@"":user.nickname forKey:@"nickname"];
            [dics setObject:user.headsmall==nil?@"":user.headsmall forKey:@"headsmall"];
            [dics setObject:user.uid==nil?@"":user.uid forKey:@"uid"];
            [datas addObject:dics];

        }
        data = datas;
        [_table reloadData];
    } failure:^(id result) {[SVProgressHUD dismiss];
        [SVProgressHUD showErrorWithStatus:result];
    }];
  
    
    [[NSNotificationCenter defaultCenter]
     addObserver:self
     selector:@selector(addphoto:)
     name:@"addphoto"
     object:nil];
    
    [[NSNotificationCenter defaultCenter]
     addObserver:self
     selector:@selector(addvideo:)
     name:@"addvideo"
     object:nil];
}
-(void)addvideo:(NSNotification *)not{
    if ([AppDelegate shareDelegate].isfollowvc == 1 && [AppDelegate shareDelegate].isfollowvc != 0) {
        return;
    }
    [[NSNotificationCenter defaultCenter ]postNotificationName:@"dtbackaction" object:_videoUrl];
    filetype = 2;
    VideoPath =  not.object;
    videoData = [NSData dataWithContentsOfURL:VideoPath];
    [_table reloadData];
}
-(void)addphoto:(NSNotification *)not{
    if ([AppDelegate shareDelegate].isfollowvc == 1 && [AppDelegate shareDelegate].isfollowvc != 0) {
        return;
    }
    [[NSNotificationCenter defaultCenter ]postNotificationName:@"dtbackaction" object:_videoUrl];
    filetype = 1;
    imageData = not.object;
    [_table reloadData];
    [AppDelegate shareDelegate].islod = NO;
}
#pragma  mark 高德
- (void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation
{
    if (updatingLocation)
    {
        _mapView.delegate = nil;
            locationdic = [[NSMutableDictionary alloc]init];
            [locationdic setObject:[NSString stringWithFormat:@"%f",userLocation.location.coordinate.latitude] forKey:@"lat"];
            [locationdic setObject:[NSString stringWithFormat:@"%f",userLocation.location.coordinate.longitude] forKey:@"lng"];
        
    }
}
////工程启动时保存定位
//-(void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation{
//    [locService stopUserLocationService];
//    locationdic = [[NSMutableDictionary alloc]init];
//    [locationdic setObject:[NSString stringWithFormat:@"%f",userLocation.location.coordinate.latitude] forKey:@"lat"];
//    [locationdic setObject:[NSString stringWithFormat:@"%f",userLocation.location.coordinate.longitude] forKey:@"lng"];
//    ;
//}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if ([scrollView isKindOfClass:[UITextView class]]) {
        return;
    }
    [self.view endEditing:YES];
}
#pragma mark 发布
-(void)submitAction:(NSNotification *)notification{
    [self.view endEditing:YES];
    UITextView *cont = (UITextView *)[_table viewWithTag:110];
    if ([cont.text isEqualToString:@"添加内容"]) {
        [SVProgressHUD showInfoWithStatus:@"请添加内容"];
        return;
    }
    [locationdic setObject:cont.text forKey:@"title"];
//    [locationdic setObject:[_titlefield.text trim] forKey:@"title"];
    [locationdic setObject:[AppDelegate shareDelegate].user.uid forKey:@"uid"];
    NSMutableString *str = [[NSMutableString alloc]init];
    if (sdata.count!=0) {
        for (NSMutableDictionary *dic in sdata) {
            [str appendFormat:@"%@,",[dic objectForKey:@"uid"]];
        }
    }
    [locationdic setObject:str forKey:@"touids"];
//    NSMutableArray *imgdata =[[NSMutableArray alloc]init];
//    NSMutableDictionary *dici = [[NSMutableDictionary alloc]init];
//    if (videoData) {
////        [dici setObject:@"file" forKey:@"key"];
//        [dici setObject:@"video" forKey:@"key"];
//        [dici setObject:videoData forKey:@"value"];
//        [dici setObject:@"file" forKey:@"key"];
//        [dici setObject:[self getVideoPreViewImage:VideoPath] forKey:@"value"];  //xhw2018-2-12加
//        [imgdata addObject:dici];
//    }else if(imageData){
//        [dici setObject:@"file" forKey:@"key"];
//        [dici setObject:UIImagePNGRepresentation(imageData) forKey:@"value"];
//        [imgdata addObject:dici];
//    }
//    NSLog(@"locationdic->%@",locationdic);
//    NSLog(@"imgdata->%@",imgdata);
//    NSMutableURLRequest *request = [[BusinessService shareInstance]postRequestWithURL:publish_dynamicurl postParems:locationdic data:imgdata];
//    [[NSURLConnection connectionWithRequest:request delegate:self] start];
    
    NSMutableArray *dataArr = [[NSMutableArray alloc] init];
    NSMutableDictionary *videoDataDic = [[NSMutableDictionary alloc] init];
    NSMutableDictionary *videoImgDataDic = [[NSMutableDictionary alloc] init];
    NSMutableDictionary *imgDataDic = [[NSMutableDictionary alloc] init];
    
    
    if (videoData) {
        
        NSLog(@"哈哈");
        MPMoviePlayerController *player = [[MPMoviePlayerController alloc]initWithContentURL:VideoPath];
        UIImage  *thumbnail = [player thumbnailImageAtTime:1.0 timeOption:MPMovieTimeOptionNearestKeyFrame];
        [videoDataDic setObject:@"video" forKey:@"key"];
        [videoDataDic setObject:videoData forKey:@"value"];
        [videoImgDataDic setObject:@"imagefile" forKey:@"key"];
        [videoImgDataDic setObject:UIImagePNGRepresentation(thumbnail) forKey:@"value"];
        [dataArr addObject:videoDataDic];
        [dataArr addObject:videoImgDataDic];
    }else if(imageData){
        [imgDataDic setObject:@"file" forKey:@"key"];
        [imgDataDic setObject:UIImagePNGRepresentation(imageData) forKey:@"value"];

        [dataArr addObject:imgDataDic];
    }
    

    NSMutableURLRequest *request = [[BusinessService shareInstance]postRequestWithURL:publish_dynamicurl postParems:locationdic data:dataArr];
    [[NSURLConnection connectionWithRequest:request delegate:self] start];
    [SVProgressHUD showWithStatus:@"发送中..."];
}
- (void)connection:(NSURLConnection *)connection didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite {
    float progress = [[NSNumber numberWithInteger:totalBytesWritten] floatValue];
    float total = [[NSNumber numberWithInteger: totalBytesExpectedToWrite] floatValue];
    float progres = progress/total;
    [SVProgressHUD showProgress:progres status:@"发布中..."];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)datas{
    NSString *request= [[NSString alloc] initWithData:datas encoding:NSUTF8StringEncoding];
    NSMutableDictionary *result = [NSMutableDictionary dictionary];
    result = [ValidateHelper jsonStringToDictionary:request];
    int code = [[[result objectForKey:@"state"] objectForKey:@"code"] intValue];
    if(code == 0){
        [SVProgressHUD dismiss];
        [SVProgressHUD showSuccessWithStatus:@"发布成功"];
        //xhw2018-1-12改bug14888:要装载了self的mainCtrl pop出栈
        [self.mainCtrl.navigationController popViewControllerAnimated:YES];
        //创建通知
        dispatch_async(dispatch_get_main_queue(), ^{
            NSNotification *notification = [NSNotification notificationWithName:@"public" object:nil userInfo:nil];
            [[NSNotificationCenter defaultCenter] postNotification:notification];
        });
        [[NSNotificationCenter defaultCenter ]postNotificationName:@"backAction" object:nil];
    }else{
        [SVProgressHUD showErrorWithStatus:[[result objectForKey:@"state"] objectForKey:@"msg"]];
    }
}


-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 4;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section==0) {
        return 3;
    }
    if(section == 1){
        return contentArr.count;
    }
    if (section == 2) {
        return 1;
    }
    if (section == 3) {
        return data.count;
    }
    return 0;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 1;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            return 90;
        }
        if (indexPath.row == 1) {
            return 70;
        }
        if (indexPath.row == 2) {
            return 30;
        }
     }
     if (indexPath.section == 2) {
        return 30;
    }
     return 45;
  
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
    cell.textLabel.font = [UIFont systemFontOfSize:14];
    if(indexPath.section == 0){
        if (indexPath.row == 0) {
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            ReleaseCell *cell = [tableView dequeueReusableCellWithIdentifier:@"rcell"];
            
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            if (filetype == 1) {
//                UIImage  *img = [UIImage imageWithData:imageData];
                cell.bgImg.image = imageData;
//                cell.photoBtn.hidden = YES;
//                cell.videoBtn.hidden = YES;
                [cell.photoBtn addTarget:self action:@selector(photoAction:) forControlEvents:UIControlEventTouchUpInside];

            }else if (filetype == 2){
                MPMoviePlayerController *player = [[MPMoviePlayerController alloc]initWithContentURL:VideoPath];
                UIImage  *thumbnail = [player thumbnailImageAtTime:1.0 timeOption:MPMovieTimeOptionNearestKeyFrame];
                cell.bgImg.image = thumbnail;
                
                [cell.photoBtn setImage:nil forState:UIControlStateNormal];
                [cell.videoBtn setImage:nil forState:UIControlStateNormal];
                
                cell.playBtn.hidden = NO;
                [cell.playBtn addTarget:self action:@selector(photoAction:) forControlEvents:UIControlEventTouchUpInside];
            }
            cell.textview.delegate = self;
            return cell;
        }
        if (indexPath.row == 1) {
            cell.textLabel.text = @"收件人:";
            UIScrollView *scroll = [[UIScrollView alloc]initWithFrame:CGRectMake(80, 0, SCRE_WIDTH-70, 70)];
            int x = 0;
            for (int i = 0; i < sdata.count; i++) {
                UIImageView *logimg = [[UIImageView alloc]initWithFrame:CGRectMake(x, 70/2-15, 35, 35)];
                NSMutableDictionary *user = [sdata objectAtIndex:i];
                 if ([user objectForKey:@"headsmall"]!=nil) {
                    [ValidateHelper setImage:[user objectForKey:@"headsmall"] img:logimg istoux:YES];
                }else{
                    logimg.image = [UIImage imageNamed:@"dtadd"];
                }
                logimg.layer.cornerRadius = logimg.frame.size.width/2;
                logimg.clipsToBounds = YES;
                [scroll addSubview:logimg];
                BaseButton *btn = [[BaseButton alloc]initWithFrame:logimg.frame];
                btn.tag = indexPath.section;
                btn.index = i;
                [btn addTarget:self action:@selector(imgTouchAction:) forControlEvents:UIControlEventTouchUpInside];
                [scroll addSubview:btn];
                x = (i+1)*45;
            }
            [cell.contentView addSubview:scroll];
        }
        if (indexPath.row == 2) {
            cell.textLabel.text = @"最近联系";
        }
    }
    if (indexPath.section == 1) {
        NSMutableDictionary *user = [contentArr objectAtIndex:indexPath.row];
        ReleaseCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ReleaseCell"];
        cell.head_img.layer.cornerRadius = cell.head_img.frame.size.width/2;
        cell.head_img.clipsToBounds = YES;
        [ValidateHelper setImage:[user objectForKey:@"headsmall"] img:cell.head_img istoux:YES];
        cell.ok_btn.dic = user;
        cell.ok_btn.index = (int)indexPath.section;
        cell.name_label.text = [user objectForKey:@"nickname"];
        return cell;
        return cell;
    }
    if(indexPath.section == 2){
        cell.textLabel.text = @"关注";
    }
    if (indexPath.section == 3) {
        NSMutableDictionary *user = [data objectAtIndex:indexPath.row];
        ReleaseCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ReleaseCell"];
        cell.head_img.layer.cornerRadius = cell.head_img.frame.size.width/2;
        cell.head_img.clipsToBounds = YES;
        [ValidateHelper setImage:[user objectForKey:@"headsmall"] img:cell.head_img istoux:YES];
        cell.ok_btn.dic = user;
        cell.ok_btn.index = (int)indexPath.section;
        cell.name_label.text = [user objectForKey:@"nickname"];
        return cell;
    }
    return cell;
}
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    NSUInteger proposedNewLength = textView.text.length - range.length + text.length;
    if ([textView.text isEqualToString:@"添加内容"]||[textView.text isEqualToString:@"评论"]) {
        textView.text = @"";
    }
    if(text.length==0){
        return YES;
    }
    if (proposedNewLength > 300)
        return NO;//限制长度
    return YES;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
//            AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
//            
//            if (authStatus == AVAuthorizationStatusRestricted ||  authStatus ==AVAuthorizationStatusDenied){
//                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"警告" message:@"加载相机失败，请确认隐私设置中相机权限已打开！" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
//                [alert show];
//                return;
//            }
//            UIImagePickerController *imagePickerVC = [[UIImagePickerController alloc] init];
//            imagePickerVC.sourceType = UIImagePickerControllerSourceTypeCamera;
//            imagePickerVC.delegate = self;
//            imagePickerVC.allowsEditing = YES;
//            [self presentViewController:imagePickerVC
//                               animated:NO
//                             completion:nil];
        }
    }
}
- (IBAction)okAction:(BaseButton *)sender {
    sender.selected = !sender.selected;
    if (sender.selected) {
        [sdata addObject:sender.dic];
    }else{
        [sdata removeObject:sender.dic];
    }
    [_table reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:1 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
}
- (IBAction)photoAction:(UIButton *)sender {
//    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
//    
//    if (authStatus == AVAuthorizationStatusRestricted ||  authStatus ==AVAuthorizationStatusDenied){
//        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"警告" message:@"加载相机失败，请确认隐私设置中相机权限已打开！" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
//        [alert show];
//        return;
//    }
//    UIImagePickerController *imagePickerVC = [[UIImagePickerController alloc] init];
//    imagePickerVC.sourceType = UIImagePickerControllerSourceTypeCamera;
//    imagePickerVC.delegate = self;
//    imagePickerVC.allowsEditing = YES;
//    [self presentViewController:imagePickerVC
//                       animated:NO
//                     completion:nil];
    [AppDelegate shareDelegate].islod = NO;
    [AppDelegate shareDelegate].isfollowvc = 2;
    [[NSNotificationCenter defaultCenter ]postNotificationName:@"tophoto" object:nil];
    
}
- (IBAction)vidoAction:(UIButton *)sender {
//    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
//    
//    if (authStatus == AVAuthorizationStatusRestricted ||  authStatus ==AVAuthorizationStatusDenied){
//        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"警告" message:@"加载相机失败，请确认隐私设置中相机权限已打开！" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
//        [alert show];
//        return;
//    }
//    UIImagePickerController *imagePickerVC = [[UIImagePickerController alloc] init];
//    imagePickerVC.sourceType = UIImagePickerControllerSourceTypeCamera;
//    NSString *requiredMediaType1 = ( NSString *)kUTTypeMovie;
//    
//    NSArray *arrMediaTypes=[NSArray arrayWithObjects: requiredMediaType1,nil];
//    imagePickerVC.mediaTypes = arrMediaTypes;
//    imagePickerVC.delegate = self;
//    imagePickerVC.allowsEditing = YES;
//    [self presentViewController:imagePickerVC
//                       animated:NO
//                     completion:nil];
    
}



- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    
    imageData = UIImageJPEGRepresentation([info objectForKey:UIImagePickerControllerEditedImage],0.00001);
    if(imageData){
        filetype = 1;
        [_table reloadData];
    }else{
        VideoPath = [info valueForKey:UIImagePickerControllerMediaURL];
        videoData = [NSData dataWithContentsOfURL:VideoPath];
        filetype = 2;
        [_table reloadData];
    }
    [picker dismissViewControllerAnimated:YES completion:nil];
    CGRect f =  _table.frame;
    f.origin.y = 118;
    _table.frame = f;
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
    CGRect f =  _table.frame;
    f.origin.y = 118;
    _table.frame = f;
}


#pragma mark 播放
-(void)playVideo{
    moviePlayer = [ValidateHelper bofang:VideoPath];
    [[[[UIApplication sharedApplication] windows] firstObject] addSubview:moviePlayer.view];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playVideoFinished:) name:MPMoviePlayerPlaybackDidFinishNotification object:moviePlayer];
}
#pragma  mark 视频播放
- (void)playVideoFinished:(NSNotification *)theNotification{
    self.navigationController.navigationBarHidden = NO;
    // 取消监听
    [[NSNotificationCenter defaultCenter]
     removeObserver:self name:MPMoviePlayerPlaybackDidFinishNotification object:moviePlayer];
    // 将视频视图从父视图中删除
    [moviePlayer.view removeFromSuperview];
}


-(void)imgTouchAction:(BaseButton *)btn{
    
}

// 获取视频第一帧
- (UIImage*) getVideoPreViewImage:(NSURL *)path
{
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:path options:nil];
    AVAssetImageGenerator *assetGen = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    assetGen.appliesPreferredTrackTransform = YES;
    CMTime time = CMTimeMakeWithSeconds(0.0, 600);
    NSError *error = nil;
    CMTime actualTime;
    CGImageRef image = [assetGen copyCGImageAtTime:time actualTime:&actualTime error:&error];
    UIImage *videoImage = [[UIImage alloc] initWithCGImage:image];
    CGImageRelease(image);
    return videoImage;
}


@end
